/* Copyright (c) 2019, Guillaume Champagne
 * All rights reserved.
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree.
 */

#include "porting_layer.h"
#include <math.h>

#define NB_ITER 1000
#define NB_TASK 50

no_task_retval_t monitor(no_task_argument_t args);
no_task_retval_t task(no_task_argument_t args);
no_task_retval_t jitter_initialize_test(no_task_argument_t args);

no_task_handle_t tasks_handle[NB_TASK + 1];
char tasks_name[NB_TASK][5];

DECLARE_TIME_COUNTERS(no_time_t, _)

no_main_retval_t main(no_main_argument_t args)
{
	no_initialize_test(jitter_initialize_test);
	return MAIN_DEFAULT_RETURN;
}

no_task_retval_t jitter_initialize_test(no_task_argument_t args)
{
	int32_t i;

	for (i = 0; i < NB_TASK; i++)
	{
		tasks_name[i][0] = 65;
		tasks_name[i][1] = (65 + i) % 255;
		tasks_name[i][2] = (66 + i) % 255;
		tasks_name[i][3] = (67 + i) % 255;
		tasks_name[i][4] = '\0';
		tasks_handle[i] = no_create_task(task, tasks_name[i], LITE_PRIO);
	}

	tasks_handle[NB_TASK] = no_create_task(monitor, "MON", BASE_PRIO);

	no_join_task(tasks_handle[NB_TASK]);

	no_serial_write("\nTest end\n");
}

no_task_retval_t task(no_task_argument_t args)
{
	int32_t i;
	unsigned long _workload_results[100];

	while (1)
	{
		DO_WORKLOAD(i % 100)
		no_task_yield();
		i++;
	}

	no_task_suspend_self();

	return TASK_DEFAULT_RETURN;
}

no_task_retval_t monitor(no_task_argument_t args)
{
	int32_t i;
	long diff;

	DECLARE_TIME_COUNTERS(no_time_t, time)
	DECLARE_TIME_STATS(int64_t);

	for (i = 0; i < NB_ITER; i++)
	{
		ADD_T1_COUNTER(time, 500000000)
		no_task_delay(500);
		WRITE_T2_COUNTER(time);
		COMPUTE_TIME_STATS(time, i);
		no_task_yield();
	}

	REPORT_BENCHMARK_RESULTS("-- Jitter results --")

	no_task_suspend_self();

	return TASK_DEFAULT_RETURN;
}
